﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Windows.Admin.Domain;
using Windows.Admin.Infrastructure.EFCore;
using Windows.Infrastructure.EFCore.Share.Extensions;
using Windows.Infrastructure.Share.CustomException;
using Windows.Infrastructure.Share.Extensions;
using Windows.Infrastructure.Share.Tools;
using Windows.Service.Share;

namespace Windows.Admin.Service
{
    public class PostLevelService : IPostLevelService
    {
        private readonly IMapper _mapper;
        //private readonly ICache _cache;
        private readonly AdminDbContext _db;
        public PostLevelService(IMapper mapper, AdminDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }
        /// <summary>
        /// 获取职级列表基础资料
        /// </summary>
        /// <returns></returns>
        public async Task<List<PostLevelResponse>> GetBasicPostLevels()
        {
            var posts = await _db.PostLevel.ToListAsync();
            return _mapper.Map<List<PostLevelResponse>>(posts);
        }
        /// <summary>
        /// 职级视图
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageResponse<PostLevelResponse>> Query(PageRequest<PostLevelRequest> request)
        {
            var query = Where(request);
            var list = await query.Paging(request.PageIndex, request.PageSize).ToListAsync();
            var response = new PageResponse<PostLevelResponse>
            {
                TotalCount = await query.CountAsync(),
                PageIndex = request.PageIndex,
                PageSize = request.PageSize,
                List = _mapper.Map<List<PostLevelResponse>>(list)
            };
            return response;
        }
        /// <summary>
        /// 获取id的职级详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<PostLevelResponse> Detail(int id)
        {
            var model = await _db.PostLevel.FindByIdAsync(id);
            return _mapper.Map<PostLevelResponse>(model);
        }
        /// <summary>
        /// 职级保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(PostLevelSaveRequest request)
        {
            if (_db.PostLevel.Any(x => x.Code.ToLower() == request.Code && x.Id != request.Id))
                throw new ApiException("职级编码已存在!");
            if (_db.PostLevel.Any(x => x.Name.ToLower() == request.Name && x.Id != request.Id))
                throw new ApiException("职级名称已存在!");
            PostLevel model = _mapper.Map<PostLevel>(request);
            if (request.Id != null)
            {
                model = await _db.PostLevel.FindByIdAsync(request.Id.Value) ?? throw new ApiException("岗位不存在!");
                model.Level = request.Level;
                model.Code = request.Code;
                model.Name = request.Name;
                model.Sort = request.Sort;
                model.Remark = request.Remark;
            }
            if (request.Id == null)
                await _db.PostLevel.AddAsync(model);
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 职级删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task Remove(IdsRequest request)
        {
            var names = await _db.PostLevel.Include(x => x.Posts).Where(x => request.Ids.Contains(x.Id) && x.Posts.Count > 0).Select(s => s.Name).ToListAsync();
            if (names.Count > 0)
            {
                throw new ApiException($"职级:{string.Join(',', names)}已被分配,不允许删除!");
            }
            await _db.PostLevel.RemoveAsync(request.Ids);
            await _db.SaveChangesAsync();
        }
        private IQueryable<PostLevel> Where(PageRequest<PostLevelRequest> request)
        {
            IQueryable<PostLevel> query = _db.PostLevel.AsQueryable();
            if (!request.Query.Code.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Code!));
            }
            if (!request.Query.Name.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Name!));
            }
            return query;
        }
    }
}
